package cn.kailangtu.dataspot.activify;

import android.util.Log;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.security.Key;
import java.util.List;
import cn.kailangtu.commonevents.data.DataBean;
import cn.kailangtu.commonevents.eventEntity.ControlsClickEvent;
import cn.kailangtu.commonevents.eventEntity.ControlsClickSubEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardNumberCloseEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardNumberOpenEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardSelectionCloseEvent;
import cn.kailangtu.commonevents.eventEntity.KeyboardSelectionOpenEvent;
import cn.kailangtu.commonevents.eventEntity.LocalSettingChangedEvent;
import cn.kailangtu.commonevents.eventEntity.WriteDataToMachineEvent;
import cn.kailangtu.commontools.APPSPUtils;
import cn.kailangtu.commontools.CommonUtils;
import cn.kailangtu.commontools.KeyboardUtils;
import cn.kailangtu.commontools.Loggers;
import cn.kailangtu.dataspot.R;
import cn.kailangtu.dataspot.data.ControlTree;
import cn.kailangtu.dataspot.data.consts.ControlAction;
import cn.kailangtu.dataspot.data.consts.ControlEventValues;
import cn.kailangtu.dataspot.data.context.KeyboardSelectContext;
import cn.kailangtu.dataspot.data.context.KeyboardTargetContext;
import cn.kailangtu.dataspot.logs.OptionLog;
import cn.kailangtu.dataspot.status;
import cn.kailangtu.dataspot.tasks.BaseTask;
import cn.kailangtu.serialutils.api.Com1;
import cn.kailangtu.serialutils.modbus.modbusUtil;

public abstract class  BaseFragment extends Fragment {
    String TAG = "CONTROL";



    @Override
    public void onStart() {
        super.onStart();
        buildControlTree();
        EventBus.getDefault().register(this);
        if(controlTree != null && controlTree.getRootNode().hasChild())
        {
            controlTree.setSelectNode(controlTree.getRootNode().getChildren().get(0));
            processControlsEvent(ControlAction.Selection);
        }
        resetPageIndex();
        resetPlatform();
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ControlsClickSubEvent event){
        status.resetLastOptionTime();
        /*
        if(processControlsEvent(event) == 0)
        {
            EventBus.getDefault().post(new ControlsClickEvent(0));
            EventBus.getDefault().post(new ControlsClickEvent(event.getClickValue()));
        }

         */
        Log.d(TAG,"进入onMessageEvent:"+event.getClickValue());
        switch(event.getClickValue()) {
            case ControlEventValues.ENTRY:
                /*
                收到确认按钮，判断是否选择了控件，没选择不触发该事件
                如果没有子控件，进入该控件的设置
                如果有子控件，进入子控件，并自动选择子控件最左的控件
                 */
                Log.d(TAG,"进入onMessageEvent==>Entry");
                if(controlTree != null &&  controlTree.getSelectNode() != null) {
                    if (controlTree.getSelectNode().hasChild()) {
                        //进入子项
                        if(controlTree.getSelectNode().isNeedClick())
                        {
                            click(controlTree.getSelectNode().getIndex());
                        }
                        controlTree.setSelectNode(controlTree.getSelectNode().getChildren().get(0));
                        processControlsEvent(ControlAction.Selection);
                    } else if(controlTree.getSelectNode().isEntryToClick()){

                        Log.d("SHOOTLEESSSSSSS","进来了");

                        EventBus.getDefault().post(new WriteDataToMachineEvent(1, controlTree.getSelectNode().getAddress(), controlTree.getSelectNode().getWriteValue()));


                        Log.d("SHOOTLEESSSSSSS","writeValue"+controlTree.getSelectNode().getWriteValue());
                        Log.d("SHOOTLEESSSSSSS",CommonUtils.ByteArrayToHexString( modbusUtil.writeToOne(1,
                                CommonUtils.int2ByteArray(controlTree.getSelectNode().getAddress()),
                                CommonUtils.int2ByteArray(controlTree.getSelectNode().getWriteValue()))));


                        OptionLog.log(controlTree.getSelectNode().getOptionTitle(),controlTree.getSelectNode().getWriteValue().toString(),0);
                    }
                    else {
                        //自定义处理，一般按Entry是要打开键盘
                        processControlsEvent(ControlAction.Entry);
                    }
                }
                break;
            case ControlEventValues.LEFT:
                Log.d(TAG,"进入onMessageEvent==>Left");
                if(controlTree != null && controlTree.getSelectNode() != null)
                {
                    boolean isProcess = false;
                    while(!isProcess) {
                        Log.d(TAG, "进入onMessageEvent==>Left2,," + controlTree.getSelectNode().getIndex());
                        if (controlTree.getSelectNode().getLeft() != null) {
                            Log.d(TAG, "进入onMessageEvent==>Left3");
                            controlTree.setSelectNode(controlTree.getSelectNode().getLeft());
                            processControlsEvent(ControlAction.Selection);
                            TextView textView =  this.getActivity().findViewById(controlTree.getSelectNode().getIndex());
                            if(textView.getVisibility()== TextView.VISIBLE)
                            {
                                isProcess = true;
                            }
                        } else {
                            if (controlTree.getSelectNode().getParent() != null && controlTree.getSelectNode().getParent().isRealNode()) {
                                Log.d(TAG, "进入onMessageEvent==>Left4");
                                if (controlTree.getSelectNode().getParent().isNeedClick()) {
                                    click(controlTree.getSelectNode().getParent().getIndex());
                                }
                                controlTree.setSelectNode(controlTree.getSelectNode().getParent());
                                processControlsEvent(ControlAction.Selection);
                            } else {
                                Log.d(TAG, "进入onMessageEvent==>Left5");
                                subToMain(event.getClickValue());

                            }
                            isProcess = true;
                        }
                    }
                }
                else if(controlTree.getRootNode().hasChild())
                {
                    controlTree.setSelectNode(controlTree.getRootNode().getChildren().get(controlTree.getRootNode().getChildren().size()-1));
                    processControlsEvent(ControlAction.Selection);
                }
                else {
                    subToMain(event.getClickValue());
                }
                break;
            case ControlEventValues.RIGHT:


                Log.d(TAG,"进入onMessageEvent==>Right");
                if(controlTree != null && controlTree.getSelectNode() != null)
                {
                    boolean isProcess = false;
                    while(!isProcess) {
                        Log.d(TAG, "进入onMessageEvent==>Right,INDEX:" + controlTree.getSelectNode().getIndex());
                        if (controlTree.getSelectNode().getRight() != null) {
                            Log.d(TAG, "进入onMessageEvent==>Right==>setRight");
                            controlTree.setSelectNode(controlTree.getSelectNode().getRight());
                            processControlsEvent(ControlAction.Selection);
                            TextView textView =  this.getActivity().findViewById(controlTree.getSelectNode().getIndex());
                            if(textView.getVisibility()== TextView.VISIBLE)
                            {
                                isProcess = true;
                            }
                        } else {
                            if (controlTree.getSelectNode().getParent() != null && controlTree.getSelectNode().getParent().isRealNode()) {
                                if (controlTree.getSelectNode().getParent().isNeedClick()) {
                                    click(controlTree.getSelectNode().getParent().getIndex());
                                }
                                Log.d(TAG, "进入onMessageEvent==>Right==>setParent");
                                controlTree.setSelectNode(controlTree.getSelectNode().getParent());
                                processControlsEvent(ControlAction.Selection);
                            } else {
                                Log.d(TAG, "进入onMessageEvent==>Right==>subToMain");
                                subToMain(event.getClickValue());

                            }
                            isProcess = true;
                        }
                    }
                }
                else if(controlTree.getRootNode().hasChild())
                {
                    Log.d(TAG,"进入onMessageEvent==>Right==>setRight");
                    controlTree.setSelectNode(controlTree.getRootNode().getChildren().get(0));
                    processControlsEvent(ControlAction.Selection);
                }
                else {
                    subToMain(event.getClickValue());
                }
                break;
        }
    }

    private void subToMain(int eventValue)
    {
        controlTree.setSelectNode(null);
        EventBus.getDefault().post(new ControlsClickEvent(ControlEventValues.SUB_TO_MAIN));
        EventBus.getDefault().post(new ControlsClickEvent(eventValue));
    }


    protected ControlTree controlTree;

    /**
     *
     * @param eventType
     * @return
     */
    protected abstract int processControlsEvent(int eventType);

    protected abstract void buildControlTree();


    protected abstract  void resetPageIndex();

    private void click(int sourceId)
    {
        this.getActivity().findViewById(sourceId).callOnClick();
    }

    protected void openKeybaord() {
        if (controlTree.getSelectNode().getProcessType() == 5) {
            getActivity().findViewById(controlTree.getSelectNode().getIndex()).callOnClick();
        } else if (controlTree.getSelectNode().getTargetControlId() > 0) {
            KeyboardTargetContext.controlTreeNode = controlTree.getSelectNode();

            if (controlTree.getSelectNode().getSelection() != null
                    && controlTree.getSelectNode().getSelection().size() > 0
            ) {
                KeyboardTargetContext.keyboardTargetControl = this.getActivity().findViewById(controlTree.getSelectNode().getTargetControlId());
                List<DataBean<Integer>> ls = controlTree.getSelectNode().getSelection();
                KeyboardSelectionOpenEvent event = new KeyboardSelectionOpenEvent(KeyboardTargetContext.getCurrentDataBean(ls), ls);
                EventBus.getDefault().post(event);
            } else {
                KeyboardTargetContext.keyboardTargetControl = this.getActivity().findViewById(controlTree.getSelectNode().getTargetControlId());
                if (KeyboardTargetContext.controlTreeNode.isTaskOldValue()) {
                    KeyboardNumberOpenEvent keyboardNumberOpenEvent = new KeyboardNumberOpenEvent(KeyboardUtils.getRealNumberValue(KeyboardTargetContext.getCurrentNumberValue()));
                    EventBus.getDefault().post(keyboardNumberOpenEvent);
                } else {
                    KeyboardNumberOpenEvent keyboardNumberOpenEvent = new KeyboardNumberOpenEvent("");
                    EventBus.getDefault().post(keyboardNumberOpenEvent);
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(KeyboardNumberCloseEvent event){
        Loggers.testInfo("进入数字键盘关闭事件");
        if(!event.isCancel()){
            Loggers.testInfo("进入数字键盘关闭事件,isCancel is false");
            if(KeyboardTargetContext.controlTreeNode != null){
                Loggers.testInfo("进入数字键盘关闭事件,controlTreeNode is not null");
                if(KeyboardTargetContext.controlTreeNode.getProcessType() == 0 ) {
                    Loggers.testInfo("进入数字键盘关闭事件,processType is 0");
                    Float fNewValue =  Float.valueOf( event.getResult());
                    //常规写入
                    EventBus.getDefault().post(new WriteDataToMachineEvent(1, KeyboardTargetContext.controlTreeNode.getAddress(), fNewValue.intValue()));
                    OptionLog.log(KeyboardTargetContext.controlTreeNode.getOptionTitle(),fNewValue.toString(),1);
                }
                else if(KeyboardTargetContext.controlTreeNode.getProcessType() == 2){
                    Loggers.testInfo("进入数字键盘关闭事件,processType is 2");
                    Float fNewValue =  Float.valueOf( event.getResult());
                    //扩大10倍写入
                    EventBus.getDefault().post(new WriteDataToMachineEvent(1, KeyboardTargetContext.controlTreeNode.getAddress(),Math.round(fNewValue * 10)));
                    OptionLog.log(KeyboardTargetContext.controlTreeNode.getOptionTitle(), String.valueOf(Math.round(fNewValue * 10)),1);
                }
                else if(KeyboardTargetContext.controlTreeNode.getProcessType() == 3)
                {
                    Loggers.testInfo("进入数字键盘关闭事件,processType is 3");
                   if(R.id.tvCommonSettingValueB2Low == KeyboardTargetContext.controlTreeNode.getTargetControlId()
                            || R.id.tvCommonSettingValueB2 == KeyboardTargetContext.controlTreeNode.getTargetControlId())
                    {
                        APPSPUtils.getInstance().putFangIP(event.getResult());
                        OptionLog.log("防越级，主机IP",event.getResult(),1);
                    }
                    else if(R.id.tvFactorySettingValue21 == KeyboardTargetContext.controlTreeNode.getTargetControlId()
                        || R.id.tvFactorySettingValue21Low == KeyboardTargetContext.controlTreeNode.getTargetControlId()
                    ) {

                        APPSPUtils.getInstance().putLocalIpEth0(event.getResult());
                    }
                    else if(R.id.tvFactorySettingValue22 == KeyboardTargetContext.controlTreeNode.getTargetControlId()
                        || R.id.tvFactorySettingValue22Low == KeyboardTargetContext.controlTreeNode.getTargetControlId()
                    ) {

                        APPSPUtils.getInstance().putLocalMaskEth0(event.getResult());
                    }
                    else if(R.id.tvFactorySettingValue23 == KeyboardTargetContext.controlTreeNode.getTargetControlId()
                        || R.id.tvFactorySettingValue23Low == KeyboardTargetContext.controlTreeNode.getTargetControlId()
                    ) {
                        APPSPUtils.getInstance().putLocalIpEth1(event.getResult());
                    }
                    else if(R.id.tvFactorySettingValue24 == KeyboardTargetContext.controlTreeNode.getTargetControlId()
                        || R.id.tvFactorySettingValue24Low == KeyboardTargetContext.controlTreeNode.getTargetControlId()
                    ) {
                       APPSPUtils.getInstance().putLocalMaskEth1(event.getResult());
                    }
                   else if(R.id.tvFactorySettingValue25 == KeyboardTargetContext.controlTreeNode.getTargetControlId()
                           || R.id.tvFactorySettingValue25Low == KeyboardTargetContext.controlTreeNode.getTargetControlId()
                   ) {
                       APPSPUtils.getInstance().putCameraIp(event.getResult());
                   }
                    else if(R.id.tvFactorySettingValue37 == KeyboardTargetContext.controlTreeNode.getTargetControlId()
                        || R.id.tvFactorySettingValue37Low == KeyboardTargetContext.controlTreeNode.getTargetControlId()
                    ) {
                        int newValue = -1;
                        try {
                            newValue = Integer.parseInt(event.getResult());
                            if(newValue > 0) {
                                APPSPUtils.getInstance().putChatRefreshTime(newValue);
                            }
                        }
                        catch(Exception e)
                        {
                            e.printStackTrace();
                        }
                    }
                    else if(R.id.tvCommonSettingValueB2 == KeyboardTargetContext.controlTreeNode.getTargetControlId()
                    || R.id.tvCommonSettingValueB2Low == KeyboardTargetContext.controlTreeNode.getTargetControlId()
                    )
                    {
                        APPSPUtils.getInstance().putHostIp(event.getResult());
                    }


                    EventBus.getDefault().post(new LocalSettingChangedEvent());
                }
                else if(KeyboardTargetContext.controlTreeNode.getProcessType() == 4){
                    Loggers.testInfo("进入数字键盘关闭事件,processType is 4");
                    Integer value = -1;
                    try{
                      value = Integer.parseInt(event.getResult());
                    }
                    catch(Exception e)
                    {}
                    if(value > -1)
                    {
                        TextView tv = getActivity().findViewById(KeyboardTargetContext.controlTreeNode.getTargetControlId());
                        tv.setText(String.valueOf(value));
                    }
                }

            }
        }
        KeyboardTargetContext.clean();

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(KeyboardSelectionCloseEvent event) {
        if(!event.isCancel())
        {
            if(KeyboardTargetContext.controlTreeNode != null){
                if(KeyboardTargetContext.controlTreeNode.getSelection() != null)
                {
                    for(int i =0;i< KeyboardTargetContext.controlTreeNode.getSelection().size();i++){
                        if( KeyboardTargetContext.controlTreeNode.getSelection().get(i).getLabel().equals(event.getResult().getLabel())){

                            if(KeyboardTargetContext.controlTreeNode.getProcessType() == 3)
                            {

                                Log.d("SHOOTLEE","SELECT LABEL:"+event.getResult().getLabel());
                                Log.d("SHOOTLEE","SELECT VALUE:"+event.getResult().getValue());

                                if( R.id.tvCommonSettingValueB1Low == KeyboardTargetContext.controlTreeNode.getTargetControlId()
                                        || R.id.tvCommonSettingValueB1 == KeyboardTargetContext.controlTreeNode.getTargetControlId())
                                {
                                    APPSPUtils.getInstance().putFangType(event.getResult().getLabel());
                                    OptionLog.log("防越级，类型",event.getResult().getLabel(),1);
                                }
                                else if(R.id.tvCommonSettingValueB3Low == KeyboardTargetContext.controlTreeNode.getTargetControlId()
                                        || R.id.tvCommonSettingValueB3 == KeyboardTargetContext.controlTreeNode.getTargetControlId())
                                {
                                    APPSPUtils.getInstance().putFangLevel(event.getResult().getLabel());
                                    OptionLog.log("防越级，级数",event.getResult().getLabel(),1);
                                }
                                else if(R.id.tvCommonSettingValueB4Low == KeyboardTargetContext.controlTreeNode.getTargetControlId()
                                        || R.id.tvCommonSettingValueB4 == KeyboardTargetContext.controlTreeNode.getTargetControlId())
                                {
                                    APPSPUtils.getInstance().putFangSwitch(event.getResult().getLabel());
                                    OptionLog.log("防越级保护",event.getResult().getLabel(),1);
                                }
                                else if(R.id.tvFactorySettingValue26Low == KeyboardTargetContext.controlTreeNode.getTargetControlId()
                                    || R.id.tvFactorySettingValue26 == KeyboardTargetContext.controlTreeNode.getTargetControlId()
                                ) {
                                    APPSPUtils.getInstance().put红外测温视频Switch(event.getResult().getLabel());
                                    OptionLog.log("设置红外测温视频",event.getResult().getLabel(),1);
                                }
                                else if(R.id.tvFactorySettingValue31 == KeyboardTargetContext.controlTreeNode.getTargetControlId()) {
                                    APPSPUtils.getInstance().putSerialPort1(event.getResult().getLabel());
                                }
                                else if(R.id.tvFactorySettingValue32 == KeyboardTargetContext.controlTreeNode.getTargetControlId()) {
                                    APPSPUtils.getInstance().putSerialBaudPort1(event.getResult().getLabel());
                                }
                                else if(R.id.tvFactorySettingValue33 == KeyboardTargetContext.controlTreeNode.getTargetControlId()) {
                                    APPSPUtils.getInstance().putSerialCheckPort1((int)event.getResult().getValue());
                                }
                                else if(R.id.tvFactorySettingValue34 == KeyboardTargetContext.controlTreeNode.getTargetControlId()) {
                                    APPSPUtils.getInstance().putSerialPort2(event.getResult().getLabel());
                                }
                                else if(R.id.tvFactorySettingValue35 == KeyboardTargetContext.controlTreeNode.getTargetControlId()) {
                                    APPSPUtils.getInstance().putSerialBaudPort2(event.getResult().getLabel());
                                }
                                else if(R.id.tvFactorySettingValue36 == KeyboardTargetContext.controlTreeNode.getTargetControlId()) {
                                    APPSPUtils.getInstance().putSerialCheckPort2((int)event.getResult().getValue());
                                }
                                else  if(R.id.tvFactorySettingValue31Low == KeyboardTargetContext.controlTreeNode.getTargetControlId()) {
                                    APPSPUtils.getInstance().putSerialPort1(event.getResult().getLabel());
                                }
                                else if(R.id.tvFactorySettingValue32Low == KeyboardTargetContext.controlTreeNode.getTargetControlId()) {
                                    APPSPUtils.getInstance().putSerialBaudPort1(event.getResult().getLabel());
                                }
                                else if(R.id.tvFactorySettingValue33Low == KeyboardTargetContext.controlTreeNode.getTargetControlId()) {
                                    APPSPUtils.getInstance().putSerialCheckPort1((int)event.getResult().getValue());
                                }
                                else if(R.id.tvFactorySettingValue34Low == KeyboardTargetContext.controlTreeNode.getTargetControlId()) {
                                    APPSPUtils.getInstance().putSerialPort2(event.getResult().getLabel());
                                }
                                else if(R.id.tvFactorySettingValue35Low == KeyboardTargetContext.controlTreeNode.getTargetControlId()) {
                                    APPSPUtils.getInstance().putSerialBaudPort2(event.getResult().getLabel());
                                }
                                else if(R.id.tvFactorySettingValue36Low == KeyboardTargetContext.controlTreeNode.getTargetControlId()) {
                                    APPSPUtils.getInstance().putSerialCheckPort2((int)event.getResult().getValue());
                                }


                            }
                            else {
                                int newValue = KeyboardTargetContext.controlTreeNode.getSelection().get(i).getValue();
                                EventBus.getDefault().post(new WriteDataToMachineEvent(1, KeyboardTargetContext.controlTreeNode.getAddress(), newValue));
                                OptionLog.log(KeyboardTargetContext.controlTreeNode.getOptionTitle(),String.valueOf(newValue),1);
                            }

                            EventBus.getDefault().post(new LocalSettingChangedEvent());
                            break;
                        }
                    }
                }
            }
        }
        KeyboardSelectContext.clean();
    }


    abstract void resetPlatform();

    protected void commonReset(ViewGroup viewGroup)
    {
        commonReset(viewGroup,-20,0);
    }
    protected void commonReset(ViewGroup viewGroup,int top,int left){
        commonReset(viewGroup,top,left,0,0);
    }

    protected void commonReset(ViewGroup viewGroup,int top,int left,int right,int bottom){
        ViewGroup.MarginLayoutParams layoutParams =  (ViewGroup.MarginLayoutParams)viewGroup.getLayoutParams();
        int newtop =  layoutParams.topMargin + top;
        int newleft = layoutParams.leftMargin + left;
        int newright = layoutParams.rightMargin + right;
        int newbottom = layoutParams.bottomMargin + bottom;
        layoutParams.setMargins(newleft,newtop,newright,newbottom);
        viewGroup.setLayoutParams(layoutParams);
    }

}
